<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sticky Header with Shadow on Intersection</title>
  <style>
    body {
      margin: 0;
      padding: 0;
    }
 
    header {
      height: 80px;
      background-color: #3498db;
      color: white;
      text-align: center;
      line-height: 80px;
      position: sticky;
      top: 0;
      z-index: 100;
    }
 
    .header-shadow {
      transition: box-shadow 0.3s ease;
    }
 
    .header-shadow.shadow {
      box-shadow: 0 2px 5px black;
    }
 
    section {
      height: 1000px;
      background-color: #ecf0f1;
      padding: 20px;
    }
  </style>
</head>
<body>
  <div id="guard"></div>
  <header id="sticky-header" class="header-shadow">Sticky Header</header>
 
  <section>
    <p>向下滚动触发sticky时展示shadow</p>
  </section>
 
  <script>
    const header = document.getElementById('sticky-header');
    const section = document.querySelector('section');
 
    const options = {
      threshold: 1
    };
    //guard滚动到可视区域以外时认为触发了shadow
    const intersectionObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          header.classList.remove('shadow');
        } else {
          header.classList.add('shadow');
        }
      });
    }, options);
 
    intersectionObserver.observe(document.getElementById('guard'));
  </script>
 
</body>
</html>